<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="listQuery.startTime"
        style="width: 140px;top:-4px"
        type="date"
        placeholder="开始日期"
        value-format="yyyy-MM-dd 00:00:00"
      />
      <el-date-picker
        v-model="listQuery.endTime"
        style="width: 140px;top:-4px"
        type="date"
        placeholder="结束日期"
        value-format="yyyy-MM-dd 23:59:59"
      />
      <!-- <el-select v-model="listQuery.noticeStatus" class="filter-item" placeholder="通知状态" :clearable="true">
        <el-option
          v-for="(item,index) in noticeStatusList"
          :key="index"
          :label="item.itemValue"
          :value="item.itemKey"
        />
      </el-select> -->
      <el-select v-model="listQuery.noticeStatus" class="filter-item" placeholder="通知类型" :clearable="true">
        <el-option label="部门通知" value="0" />
        <el-option label="个人通知" value="1" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" align="center" width="100">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center">
        <template slot-scope="{row}">
          <span>{{ row.content }}</span>
        </template>

      </el-table-column>
      <!--<el-table-column label="发布人">-->
      <!--<template slot-scope="{row}">-->
      <!--<span>{{ row.publisher }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="有效时间段" width="300" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startTime }}—{{ row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通知频率" width="80" align="center">
        <template slot-scope="{row}">
          <span>每天{{ row.frequency }}次</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.noticeStatus==='0'?'正常':'失效' }}</span>
        </template>
      </el-table-column>

      <!--<el-table-column label="通知对象">-->
      <!--<template slot-scope="{row}">-->
      <!--<span>{{ row.orgId }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            修改
          </el-button>
          <el-button type="primary" size="mini" style="width:75px" @click="manualNotice(row,$index)">
            手动通知
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 新增/编辑考卷 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <el-row>
          <el-col>
            <el-form-item label="标题" prop="title">
              <el-input v-model="temp.title" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="通知内容" prop="title">
              <el-input
                v-model="temp.content"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="推送频率" prop="title">
              <el-select v-model="temp.frequency" class="filter-item" placeholder="请选择">
                <el-option :value="1" label="每天1次" />
                <el-option :value="2" label="每天2次" />
                <el-option :value="3" label="每天3次" />
                <el-option :value="4" label="每天4次" />
                <el-option :value="5" label="每天5次" />
                <el-option :value="6" label="每天6次" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="通知状态" prop="title">
              <el-select v-model="temp.noticeStatus" class="filter-item" placeholder="请选择">
                <el-option value="0" label="正常" />
                <el-option value="1" label="停用" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="开始日期" prop="title">
              <el-date-picker
                v-model="temp.startTime"
                type="date"
                placeholder="选择日期"
                style="width:140px"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="结束日期" prop="title">
              <el-date-picker
                v-model="temp.endTime"
                type="date"
                placeholder="选择日期"
                style="width:140px"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="通知类型" prop="title">
            <el-tabs v-model="temp.noticeType" :stretch="true" @tab-click="handleTypeClick">
              <el-tab-pane label="部门" name="0">
                <el-tree
                  ref="treeTable"
                  :data="DeptTree"
                  node-key="id"
                  :expand-on-click-node="false"
                  show-checkbox
                >
                  <span slot-scope="{ node, data }" class="custom-tree-node">
                    <span>{{ data.label }}</span>
                  </span>
                </el-tree>
              </el-tab-pane>
              <el-tab-pane label="个人" name="1">
                <el-row style="margin-bottom:22px">
                  <el-form-item label="部门" prop="title">
                    <el-cascader
                      v-model="depId"
                      style="width:100%"
                      :options="DeptTree"
                      :props="{ expandTrigger: 'hover',value:'id',label:'label',emitPath:false}"
                      @change="DepChange"
                    />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="选择员工" prop="title">
                    <el-select v-model="temp.userId" class="filter-item" placeholder="请选择">
                      <el-option
                        v-for="(item,index) in empList"
                        :key="index"
                        :label="item.userName"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuareApi, editApi, getByIdApi, addApi, DeleteApi, manualNoticeApi, getDeptTree } from '@/api/sysmanage'
import { getAllUserByDeptId, getDicApi } from '@/api/public'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'Notice',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      /* eslint-disable */
        value:'',
        noticeStatusList:[],
        OrgList:[],
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          "endTime": "",
          "limit": 10,
          "noticeStatus": "",
          "page": 1,
          "startTime": ""
        },
        temp:  {
          "content": "",
          "deptId": 0,
          "endTime": "",
          "frequency": 0,
          "id": 0,
          "noticeStatus": "",
          "noticeType": "",
          "selectDeptIdList": [],
          "startTime": "",
          "title": "",
          "userId": '',
          "depId":''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false,
        updateObj:{
          index:'',
          data:[]
        },
         DeptTree:[],
         empList:[]
      }
    },
    created() {
      this.getList()
      getDicApi({dictCode:"notice_status"}).then(
        res=>{
        this.noticeStatusList= res.data
        }
      )
      // 获取部门树
      getDeptTree().then(res=>{
      console.log("TCL: created -> res", res)
        this.DeptTree=res.data
      })

    },
    methods: {
    //  手动通知
      manualNotice(row,index) {
        manualNoticeApi({id:row.id}).then(res=>{
          this.$message({
            message: "通知成功",
            type: 'success'
          })
        }).catch(err=>{
          this.$message({
            message:err.message,
            type: 'error'
          })
        })
      },
      getList() {
        this.listLoading = true
        pageQuareApi (this.listQuery,'notice').then(response => {
          this.list = response.data.list
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
       handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetTemp() {//重置修改模态框
        this.temp = {
          "content": "",
          "deptId": 0,
          "endTime": "",
          "frequency": 1,
          "noticeStatus":'0',
          "noticeType": "0",
          "selectDeptIdList": [],
          "startTime": "",
          "title": "",
          "userId": 0
        }
        this.depId=''
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.$refs.treeTable.setCheckedKeys([])//清空部门树
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid=true) {
            let depTreeList=this.$refs.treeTable.getCheckedKeys()
            this.temp.selectDeptIdList=depTreeList
            addApi(this.temp,'notice').then((res) => {
            console.log("TCL: createData -> res", res)
              let {code,data,message}=res
              if(code==='200'){
                this.$message({
                  message: message,
                  type: 'success',
                })
                this.dialogFormVisible = false
                this.list.unshift(data)
                //  this.handleFilter()//刷新重新请求
              }
            })
          }
        })
      },
      DepChange(deptId){//监听选中的部门树ID，通过部门ID获取部门下所有员工
        getAllUserByDeptId({deptId}).then(res=>{
        const {data}=res
          this.empList=data
        })
      },
      handleTypeClick(targetName, action){//切换通知类型触发的回调
      
        if( targetName.name==='1'){//1 代表个人
          this.$refs.treeTable.setCheckedKeys([]);
        }else{
          this.temp.userId=''
        }
      },
      async handleUpdate(row,index) {
        this.resetTemp()
        await getByIdApi({id:row.id},'notice').then(res=>{
        console.log("TCL: handleUpdate -> res", res)
          // this.temp = res.data
          let data=res.data
           this.temp={
              'id':row.id,
              "content": data.content||'',
              "deptId": data.deptId||'',
              "endTime": data.endTime||'',
              "frequency": data.frequency||'',
              "noticeStatus":data.noticeStatus||'',
              "noticeType": data.noticeType||'',
              "selectDeptIdList":data.deptIdList||[],
              "startTime": data.startTime||'',
              "title": data.title||'',
              "userId": data.userId||'',
            
            }
          //  console.log("TCL: handleUpdate -> this.temp", this.temp)
        })
       
        //保存修改的行数据，索引
        this.updateObj={
          index:index,
          data:row
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.$refs.treeTable.setCheckedKeys(this.temp.selectDeptIdList)//更新部门树
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid=true) {
            let depTreeList=this.$refs.treeTable.getCheckedKeys()
            this.temp.selectDeptIdList=depTreeList
            
            editApi( this.temp,'notice').then((res) => {
              this.dialogFormVisible = false
              if(res.code==='200'){
                this.$message({
                  message: res.message,
                  type: 'success',
                })
                const {index,data}=this.updateObj
                const row=Object.assign(data, this.temp)
                this.list.splice(index,1,row)
              }else{
                this.$message({
                  message: res.message||'修改失败',
                  type: 'error'
                })
              }

            })
          }
        })
      },
      handleDelete(row,index) {
        this.$confirm('此操作不可逆, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(res => {
          DeleteApi({id:row.id},'notice').then(res=>{
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.list.splice(index,1)
          }).catch(err=>{
            this.$message({
              message:err.message,
              type: 'error'
            })
          })

          // row.status = status
        })
      }
    }
  }
</script>
